// Sphere object

#include <math.h>
#include <iostream>

#include "../include/triangle.h"

#include "../my/include/Matrix.h"

// Plane defined as a vertex (in world space) as location
//                  and n which is the normal direction

Triangle::Triangle(Vertex &aa, Vertex &bb,Vertex &cc) {
	a = aa;
	b = bb;
	c = cc;
	typex = "Triangle";
	typei = 3;
}
bool Triangle::intersect(Ray &input_ray, Hit *hit) {
	//transform
	Ray ray=input_ray;
	if (transformed != 0) {
		ray.D.multiply(invers_matrix);
		ray.P.multiply(invers_matrix);
	}
	//N = (c-a)x(b-a)
	Vector N = (c-a).cross((b-a));

	//N.P’ = -d
	//N.a = -d;
	//P’ = P + tD ->  N.(P+tD) = -d -> t = N.P+N.tD = -d -> t = (-d – N.P) /N.D


	double t = (a.getVector().dot(N)
			-
			ray.P.getVector().dot(N))/N.dot(ray.D);
	if(t <0.00001){
		return false;
	}
	Vector hitPoint;
	hitPoint.x = ray.P.x + ray.D.x * t;
	hitPoint.y = ray.P.y + ray.D.y * t;
	hitPoint.z = ray.P.z + ray.D.z * t;
	int tempa = 0;
	double nx = fabs(N.x);
	double ny = fabs(N.y);
	double nz = fabs(N.z);
	if(nx > ny){
		if(nz > nx){
			//z
			tempa = 3;
		}else{
			//x
			tempa = 1;
		}
	}else{
		if(nz > ny){
			//z
			tempa = 3;
		}else{
			//y
			tempa = 2;
		}
	}

	Vector aa = a.getVector();
	Vector bb = b.getVector();
	Vector cc = c.getVector();

	Vector pp = hitPoint;
	if(tempa == 1){
		aa.x = 0;
		bb.x = 0;
		cc.x = 0;
		pp.x = 0;
	}else if(tempa == 2){
		aa.y = 0;
		bb.y = 0;
		cc.y = 0;
		pp.y = 0;
	}else if(tempa == 3){
		aa.z = 0;
		bb.z = 0;
		cc.z = 0;
		pp.z = 0;
	}

	Vector temp1 = pp.subtract(aa).cross(bb.subtract(aa));
	Vector temp2 = pp.subtract(bb).cross(cc.subtract(bb));
	Vector temp3 = pp.subtract(cc).cross(aa.subtract(cc));

	int hited = 0;
	if(tempa == 1){
		if(temp1.x>0&&temp2.x>0&&temp3.x>0){
			hited = 1;
		}
		if(temp1.x<0&&temp2.x<0&&temp3.x<0){
			hited = 1;
		}
	}else if(tempa == 2){
		if(temp1.y>0&&temp2.y>0&&temp3.y>0){
			hited = 1;
		}
		if(temp1.y<0&&temp2.y<0&&temp3.y<0){
			hited = 1;
		}
	}else if(tempa == 3){
		if(temp1.z>0&&temp2.z>0&&temp3.z>0){
			hited = 1;
		}
		if(temp1.z<0&&temp2.z<0&&temp3.z<0){
			hited = 1;
		}
	}



	if (hited != 0) {
		hit->obj = this;
		hit->t = t;

		hit->p.x = ray.P.x + t * ray.D.x;
		hit->p.y = ray.P.y + t * ray.D.y;
		hit->p.z = ray.P.z + t * ray.D.z;
		hit->p.w = 1.0;
		hit->n.x = N.x;
		hit->n.y = N.y;
		hit->n.z = N.z;

		if (transformed != 0) {
			hit->n.multiply(invers_matrix);
		}
		hit->n.normalise();

		hit->obj_mat = *this->obj_mat;

		return true;
	} else {
		return false;
	}
}
